<?php

namespace app\api\controller\v2;

use app\common\controller\Frontend;
use think\facade\Db;
use think\facade\Log;

class Extend extends Frontend
{
    /**
     * 申请成为推广员
     * @return void
     */
    public function apply (): void
    {
        $real_name = $this->request->param('real_name');
        $mobile = $this->request->param('mobile');
        $extend_area_id = $this->request->param('extend_area_id');
        $code = $this->request->param('code');

        if (empty($real_name) || empty($mobile) || empty($extend_area_id) || empty($code)) {
            $this->error('请填写完整信息');
        }

        try {
            sms_check($mobile, $code, 'apply_extend');
        } catch (\Throwable $e) {
            Log::error('验证码错误 ' . $e->getMessage() . ' mobile:' . $mobile . ' code:' . $code);
            $this->error('验证码错误，请重新输入！');
        }

        $area = Db::name('platform_area')->where('city_id', $extend_area_id)->where('status', 1)->find();
        if (!$area) {
            $this->error('当前城市未开通');
        }

        $ret = \app\common\model\User::where('id', $this->auth->id)->find();
        if ($ret->is_extend == 1) {
            $this->error('您已经是推广员');
        }


        $ret->is_extend = 1;
        $ret->extend_status = 2;
        $ret->real_name = $real_name;
        $ret->mobile = $mobile;
        $ret->extend_area_id = $extend_area_id;
        if (!$ret->save()) {
            Log::error('申请失败');
            $this->error('申请失败');
        }
        $this->success('申请成功');
    }


    /**
     * 申请提现
     * @return void
     */
    public function applyWithdrawal (): void
    {
        $params = $this->request->param();

        try {
            #验证参数
            $this->validate($params, [
                'money'       => 'require|float|>=:0.01',
                'name'        => 'require',
                'card_number' => 'require',
                'card_name'   => 'require',
                'bank'        => 'require',
            ]);
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
        }
        $ret = \app\common\model\User::where('id', $this->auth->id)->find();
        if ($ret->is_extend == 0) {
            $this->error('您还不是推广员');
        }
        if ($ret->extend_status != 1) {
            $this->error('推广员身份已被禁用');
        }
        if ($ret->extend_money < $params['money']) {
            $this->error('提现金额不足');
        }
        Db::startTrans();
        try {
            $ret->extend_money = bcsub($ret->extend_money, $params['money'], 2);
            $ret->save();

            #推广员余额变动记录
            $MoneyLog = Db::name('user_extend_money_log')->where('user_id', $this->auth->id)->order('create_time', 'desc')->find();
            $after = $MoneyLog['after'] ?? 0;
            Db::name('user_extend_money_log')->insert([
                'user_id'     => $this->auth->id,
                'money'       => $params['money'],
                'type'        => 2,
                'before'      => $after,
                'after'       => bcsub($after, $params['money'], 2),
                'memo'        => '提现',
                'create_time' => date('Y-m-d H:i:s', time())
            ]);

            #加入提现记录表
            Db::name('user_extend_withdrawal')->insert([
                'user_id'     => $this->auth->id,
                'price'       => $params['money'],
                'status'      => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'name'        => $params['name'],
                'card_number' => $params['card_number'],
                'card_name'   => $params['card_name'],
                'bank'        => $params['bank'],
            ]);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            Log::error('提现失败：user_id :' . $this->auth->id . 'errMsg' . $e->getMessage());
            $this->error('提现申请失败');
        }
        $this->success('提现申请成功');
    }


    /**
     * 获取提现记录
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getExtendWithdrawalLog (): void
    {
        $list = Db::name('user_extend_withdrawal')->where('user_id', $this->auth->id)->order('create_time', 'desc')->paginate(10);
        $this->success('获取成功', [
            'list'  => $list->items(),
            'total' => $list->total()
        ]);
    }
}